<template>
  <!-- 会话转交 -->
  <el-dialog
    :title="$t('im.imChat.components.messageBox.message.btn2')"
    :visible.sync="isForwarding"
    width="500px"
    @close="closeDialog"
  >
    <!-- 内容主体区域 -->
    <el-form
      :model="ForwardingForm"
      :rules="ForwardingRules"
      ref="ForwardingRef"
      
      label-position="top"
    >
      <el-form-item prop="customerServiceId" :label="$t('im.detail.label4')">
        <el-select
          style="width: 100%"
          :placeholder="$t('common.placeholder.select')"
          clearable
          @change="ForwardingChange"
          v-model="ForwardingForm.customerServiceId"
        >
          <el-option
            v-for="item in AllCustomerList"
            :key="item.id"
            :value="item.id"
            :label="item.label"
          >
            <div class="option-item">
              <div class="info">
                <span class="relationUserName">{{ item.customerServiceName }}</span>
                <!-- 企业微信环境，使用open-data查询数据。其他环境正常显示 -->
                <template v-if="isOpenData">
                  <span
                    style="margin-left: 10px"
                    v-if="item.relationUserStaffId"
                    >(<open-data
                      style="margin: 0"
                      type="userName"
                      :openid="item.relationUserStaffId"
                    ></open-data
                    >)</span
                  >
                </template>
                <template v-else>
                  <span
                    style="margin-left: 10px; max-width: 120px"
                    v-if="item.relationUserName"
                    class="relationUserName"
                    >({{ item.relationUserName }})</span
                  >
                </template>
              </div>
              <div class="status">
                <span class="q" :style="{ backgroundColor: item.color }"></span>
                <span>{{ item.text }}</span>
              </div>
            </div>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('im.detail.label5')">
        <el-input
          v-model="ForwardingForm.forwardRemark"
          :placeholder="$t('common.placeholder.input2')"
          resize="none"
          type="textarea"
        ></el-input>
      </el-form-item>
    </el-form>
    <div class="ForwardingTitle">
      <span class="iconfont icon-fdn-info"></span>
        {{$t('im.imChat.components.messageBox.message.tips1')}}
    </div>
    <!-- 底部区域 -->
    <span slot="footer" class="dialog-footer">
      <el-button @click="isForwarding = false">{{$t('common.base.cancel')}}</el-button>
      <el-button type="primary" @click="SaveForwarding">{{$t('common.base.confirm')}}</el-button>
    </span>
  </el-dialog>
</template>

<script>
/* util */
import { isOpenData } from '@src/util/platform';
/** api */
import * as IMApi from '@src/api/ImApi.js';
/** enum */
import { CustomerServiceWorkStatusMaps } from '@model/enum/ImEnum.js';

export default {
  name: 'SessionTransferDialog',
  props: {
    conversationId: {
      type: [Number, String],
    },
    pageFrom:{
      type:String,
      default:''
    }
  },
  data() {
    return {
      isOpenData,
      isForwarding: false,
      AllCustomerList: [],
      ForwardingItem: {},
      ForwardingForm: {
        // 当前会话ID
        conversationId: '',
        // 会话转交备注
        forwardRemark: '',
        // 转交接收者的客服账号
        customerServiceId: '',
      },
      ForwardingRules: {
        customerServiceId: {
          required: true,
          message: this.$t('im.detail.tips3'),
          trigger: ['blur'],
        },
      },
    };
  },
  methods: {
    open() {
      this.getAllCustomerService();
    },
    closeDialog() {
      this.$refs.ForwardingRef.resetFields();
    },
    // 获取会话转交数据
    ForwardingChange(id) {
      const item = this.AllCustomerList.find(item => item.id === id);
      this.ForwardingItem = item;
      this.ForwardingForm.customerServiceId = item ? item.id : '';
    },
    getAllCustomerService() {
      IMApi.getAllCustomerService().then(res => {
        const { code, message = this.$t('common.base.tip.systemIsError'), data = [] } = res;
        if (code !== 0) return this.$platform.alert(message);
        this.AllCustomerList = data.map(v => {
          return {
            ...v,
            label: v.customerServiceName,
            text: CustomerServiceWorkStatusMaps[v.status].text,
            color: CustomerServiceWorkStatusMaps[v.status].color,
          };
        });
        // 去除自己  会话详情页面不剔除自己
        if(this.pageFrom != 'imDetail'){
          let UserID = JSON.parse(window.top._init)?.user?.userId;
          this.AllCustomerList = this.AllCustomerList.filter(
            item => UserID !== item.relationUserId
          );
        }
        this.isForwarding = true;
      });
    },
    // 会话转交——提交
    SaveForwarding() {
      this.$refs.ForwardingRef.validate(async valid => {
        if (!valid) return;
        this.ForwardingForm.conversationId = this.conversationId;

        let fn = res => {
          if (res.code === 0) {
            this.$notify({
              title: this.$t('im.detail.btn2'),
              message: this.$t('im.detail.tips7'),
              type: 'success',
            });
            this.$emit('SaveCallBack');
          } else {
            this.$message.error(res?.message ?? this.$t('common.base.tip.httpIsError'));
          }
        };
        // 未绑定客服人员，给予提示
        if (!this.ForwardingItem.relationUserId) {
          this.$confirm(
            this.$t('im.imChat.components.messageBox.message.tips5'),
            this.$t('common.base.toast'),
            {
              confirmButtonText: this.$t('common.base.confirm'),
              cancelButtonText: this.$t('common.base.cancel'),
              type: 'warning',
            }
          )
            .then(() => {
              IMApi.conversationForwarding(this.ForwardingForm).then(fn);
            })
            .catch(() => {});
        } else {
          IMApi.conversationForwarding(this.ForwardingForm).then(fn);
        }
      });
    },
  },
};
</script>

<style scoped lang='scss'>
.option-item {
  display: flex;
  width: 100%;
  justify-content: space-between;
  .info {
    display: flex;
    max-width: 200px;
    .relationUserName {
      max-width: 80px;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
    }
  }
  .status {
    display: flex;
    align-items: center;
    .q {
      width: 6px;
      height: 6px;
      background-color: red;
      margin-right: 6px;
      border-radius: 100%;
    }
  }
}
</style>